package com.lan.app.interceptot;

import com.alibaba.fastjson.JSON;
import com.lan.app.constant.Constant;
import com.lan.app.repository.User;
import com.lan.app.utils.Deploy;
import com.lan.support.intercept.an.Auth;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("getRequestURL" + request.getRequestURL());
//        System.out.println("getRequestURI" + request.getRequestURI());
//        System.out.println("getContextPath" + request.getContextPath());


        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Annotation[] annos = method.getAnnotations();
            if (annos == null || annos.length == 0) {
                return true;
            }
            Auth auth = method.getAnnotation(Auth.class);
            if (auth != null) {
                User u = (User) request.getSession().getAttribute(Constant.User_Info);
                if (u == null) {
                    response.sendRedirect("/login");
                    return false;
                }
            }

//            Enumeration<String> headerNames = request.getHeaderNames();
//            boolean bool = true;
//            for (Enumeration<String> e = headerNames; e.hasMoreElements(); ) {
//                String thisName = e.nextElement().toString();
//                if ("x-token".equalsIgnoreCase(thisName)) {
//                    String token = request.getHeader(thisName);
//                    if (StringUtils.isBlank(token) || !Constant.token.equalsIgnoreCase(token)) {
//                        throw Ex.build(SExCode.NO_AUTH);
//                    }
//                    bool = false;
//                }
//            }
//
//            if (bool) {
//                throw Ex.build(SExCode.NO_AUTH);
//            }
        }
        return true;
    }

}
